package com.ycm.handler;


import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author ranqing
 * @version 1.0
 * @date 2023/6/12 10:28
 */
@Component
@Slf4j
public class MybatisFieldHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        String userId = getUserId();

        Class<?> type = metaObject.getGetterType("createTime");
        if (type.equals(LocalDateTime.class)) {
            LocalDateTime now = LocalDateTime.now();
            this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, now);
            this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, now);
        } else if (type.equals(LocalDate.class)) {
            LocalDate now = LocalDate.now();
            this.strictInsertFill(metaObject, "createTime", LocalDate.class, now);
            this.strictInsertFill(metaObject, "updateTime", LocalDate.class, now);
        } else {
            Date date = new Date();
            this.strictInsertFill(metaObject, "createTime", Date.class, date); // 起始版本 3.3.0(推荐使用)
            this.strictInsertFill(metaObject, "updateTime", Date.class, date); // 起始版本 3.3.0(推荐)
        }
        if (userId != null) {
            this.strictInsertFill(metaObject, "createUser", String.class, userId);
            this.strictInsertFill(metaObject, "updateUser", String.class, userId);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String userKey = getUserId();
        Class<?> type = metaObject.getGetterType("updateTime");
        if (type.equals(LocalDateTime.class)) {
            LocalDateTime now = LocalDateTime.now();
            this.setFieldValByName("updateTime", now, metaObject);
        } else if (type.equals(LocalDate.class)) {
            LocalDate now = LocalDate.now();
            this.setFieldValByName("updateTime", now, metaObject);
        } else {
            Date date = new Date();
            this.setFieldValByName("updateTime", date, metaObject); // 起始版本 3.3.0(推荐)
        }

        if (userKey != null) {
            this.setFieldValByName("updateUser", userKey, metaObject);
        }
    }

    private String getUserId() {
        return "admin";
    }
}
